const exp = require("express")

const verifyFn = require("../middleware/loginVerify")

const verifyFn1 = require("../middleware/loginVerify1")

const userModel = require("../database/model/useModel")
const loginVerify1 = require("../middleware/loginVerify1")
const loginVerify2 = require("../middleware/loginVerify2")

const md5 = require("md5")

const loginRouter = exp.Router()

loginRouter.post("/user", (req, res) => {
    let { username, pwd } = req.body
    userModel.find((err, data) => {
        let result = data.find(item => item.username == username && item.pwd == md5(pwd))
        // console.log(result);
        if (result) {
            req.session.username = result.username
            res.render("loginsuccess.html")
        } else {
            res.send("抱歉，您输入的账号密码有误")
        }
    })
})

loginRouter.post("/logon", (req, res) => {
    let { username, pwd } = req.body
    // console.log(username, md5(pwd));
    pwd = md5(pwd)
    userModel.create({ username, pwd }, (err, data) => {
        if (err) return;

        res.send('添加成功');
    })
    // res.send("成功")
})



loginRouter.get("/admin", loginVerify2, (req, res) => {

    userModel.find((err, data) => {
        if (err) return;
        res.render("index1.html", { data })
    })
})


loginRouter.post("/admin", loginVerify1, (req, res) => {
    req.session.username = req.body.username
    req.session.pwd = req.body.pwd
    userModel.find((err, data) => {
        if (err) return;
        res.render("index1.html", { data })
    })

})

loginRouter.get("/addUser", loginVerify2, (req, res) => {
    res.render("addUser.html")
})

loginRouter.post("/addUser", loginVerify2, (req, res) => {
    let { username, pwd } = req.body
    console.log(req.body);
    userModel.create({ username: username, pwd: md5(pwd) }, (err, data) => {
        if (!err) {
            res.render("jump.html", { data: "添加成功" })
        }


    })

})



loginRouter.get("/delete", loginVerify2, (req, res) => {
    let _id = req.query
    userModel.deleteOne({ _id }, (err, data) => {
        if (!err) {
            res.render("jump.html", { data: "删除成功" })
        }
    })


})

loginRouter.get("/add", loginVerify2, (req, res) => {
    let _id = req.query

    userModel.findById(_id, (err, data) => {


        if (!err) {
            res.render("add.html", { data })
        }
    })

})

loginRouter.post("/add", loginVerify2, (req, res) => {

    let { username, pwd, _id } = req.body
    userModel.updateOne({ _id }, { username, pwd: md5(pwd) }, (err, data) => {
        if (!err) {
            res.render("jump.html", { data: "修改成功" })
        }

    })
})

module.exports = loginRouter